package com.diandian.backend.client.service;

import com.alibaba.fastjson.JSON;
import com.diandian.backend.client.constants.ClientConstant;
import com.diandian.backend.client.dto.ClientInfoDetailParamDTO;
import com.diandian.backend.client.dto.ClientPermissionCacheDataDTO;
import com.diandian.backend.client.resp.ClientInfoDetailResp;
import com.diandian.backend.client.resp.ClientSettingListResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ClientCacheRefreshService {

    private static final Logger logger = LoggerFactory.getLogger(ClientCacheRefreshService.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ClientInfoService clientInfoService;

    @Autowired
    private ClientPermissionService clientPermissionService;

    @Autowired
    private ClientMeiTuanShanGouStoreService clientMeiTuanShanGouStoreService;

    @Autowired
    private ClientSettingService clientSettingService;

    public void refreshAllClientCache() {

        // 获取所有的clientId
        List<String> allClientIdList = clientInfoService.getAllClientId();
        if(allClientIdList == null || allClientIdList.size() == 0) {
            logger.info("当前无有效的客户端信息，停止后续处理。");
            return;
        }
        logger.info("当前获取到待刷新权限的客户端数量：{}", allClientIdList.size());

        for (int i = 0; i < allClientIdList.size(); i++) {

            String clientId = allClientIdList.get(i);

            logger.info("开始执行第{}个客户端权限刷新，客户端id：{}", i + 1, clientId);

            // 查询客户端信息
            ClientInfoDetailParamDTO queryParamDTO = new ClientInfoDetailParamDTO();
            queryParamDTO.setClientId(clientId);
            ClientInfoDetailResp clientInfoDTO = clientInfoService.getDetail(queryParamDTO);
            if(clientInfoDTO == null){
                logger.info("当前客户端信息为空，跳过后续处理。");
                continue;
            }
            String clientKey = clientInfoDTO.getClientKey(); // clientKey中不能包含短横线（-），否则导致set不生效。

            // 查询权限信息
            List<String> cmdList = clientPermissionService.getPermissions(clientId);
            if(clientInfoDTO == null){
                cmdList = new ArrayList<>();
            }

            ClientPermissionCacheDataDTO dbPermissionDTO = new ClientPermissionCacheDataDTO();
            dbPermissionDTO.setClientId(clientInfoDTO.getClientId());
            dbPermissionDTO.setClientKey(clientKey);
            dbPermissionDTO.setClientSecret(clientInfoDTO.getClientSecret());
            dbPermissionDTO.setStatus(clientInfoDTO.getStatus());
            dbPermissionDTO.setStartTime(clientInfoDTO.getStartTime());
            dbPermissionDTO.setEndTime(clientInfoDTO.getEndTime());
            dbPermissionDTO.setCmds(cmdList);

            // 设置美团闪购门店编码集合
            List<String> meiTuanShanGouStoreCodeList = clientMeiTuanShanGouStoreService.getStoreCodeListByClientId(clientId);
            if(meiTuanShanGouStoreCodeList == null){
                meiTuanShanGouStoreCodeList = new ArrayList<>();
            }
            dbPermissionDTO.setMeiTuanShanGouStoreCodes(meiTuanShanGouStoreCodeList);

            // 设置配置信息集
            List<ClientSettingListResp> settingList = clientSettingService.getList(clientId, null);
            if(settingList == null){
                settingList = new ArrayList<>();
            }
            /**
             * tempMap结构如下：
             * {
             *     "type1":{
             *         "key1": "value1",
             *         "key2":"value2"
             *     },
             *     "type2":{
             *         "key1": "value1",
             *         "key2":"value2"
             *     }
             * }
             */
            Map<String, Map<String, String>> settingMap = new HashMap();
            for (int j = 0; j < settingList.size(); j++) {
                String type = settingList.get(j).getType();
                String paramKey = settingList.get(j).getParamKey();
                String paramValue = settingList.get(j).getParamValue();

                if(settingMap.get(type) == null){
                    Map<String, String> innerMap = new HashMap<>();
                    innerMap.put(paramKey, paramValue);
                    settingMap.put(type, innerMap);
                    continue;
                }

                Map<String, String> innerMap = settingMap.get(type);
                innerMap.put(paramKey, paramValue);
            }
            dbPermissionDTO.setSetting(settingMap);

            // 缓存权限数据
            String permissionStr = JSON.toJSONString(dbPermissionDTO);
            redisTemplate.opsForValue().set(ClientConstant.CLIENT_PERMISSION_CACHE_PREFIX + clientKey, permissionStr);

            logger.info("客户端id[{}]的权限缓存完成，权限信息：{}", clientId, permissionStr);
        }
    }
}
